package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    /**
     * 1登陆
     */
    @RequestMapping("login")
    public String login(String userName, String pwd,String code, HttpServletRequest req){
   if( code.equalsIgnoreCase(req.getSession().getAttribute("code").toString())==false  ){
       return "codeError";
   }
        UserBean userBean=service.login(userName,pwd);
        if(userBean!=null){
       req.getSession().setAttribute("loginUser",userBean);
    return "ok";
}
       return "no";
    }
    /**
     * 2.首页显示登陆用户
     */
    @RequestMapping("getLogin")
    public UserBean getLogin(HttpServletRequest req){
      return (UserBean) req.getSession().getAttribute("loginUser");
    }

    /**
     * 3.注册用户
     */

    @RequestMapping("add")
    public String add(UserBean userBean,  @RequestParam("pic") MultipartFile mf) throws IOException {

        String fileName=mf.getOriginalFilename();
        fileName=System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
//        mf.transferTo(new File("/html/img/"+fileName));
        mf.transferTo(new File("E:\\z03javaProject\\p12webTest\\forum\\src\\main\\resources\\static\\html\\img\\"+fileName));
        userBean.setImgPath(fileName);
        service.add(userBean);
        return "ok";
    }

    /**
     * 4.注销登陆
     */
    @RequestMapping("exit")
    public String exit(HttpServletRequest req){
req.getSession().invalidate();
        return "exit";
    }

    @RequestMapping("checkName")
    public String checkName(String name){
       UserBean userBean= service.checkName(name);
       if(userBean!=null){
           return "no";
       }
        return "ok";
    }
}
